/**
 * 
 */
package com.lehecai.core.message.terminal;

import com.lehecai.core.message.EventType;
import com.lehecai.core.util.CoreJSONUtils;
import net.sf.json.JSONObject;

/**
 * @author gb
 *
 */
public class TerminalTimeoutMessage {

    private static final String JSON_KEY_EVENT_TYPE = "event_type";
	
	private static final String JSON_KEY_TERMINAL_ID = "terminal_id";
	
	private static final String JSON_KEY_TIMESTAMP = "timestamp";
	
	private EventType eventType;

	private Long terminalId;
	
	private Long timestamp;

	@Override
	public String toString() {
		JSONObject object = new JSONObject();

        if (eventType != null) {
		    object.put(JSON_KEY_EVENT_TYPE, eventType.getValue());
        }

		object.put(JSON_KEY_TERMINAL_ID, terminalId);
		object.put(JSON_KEY_TIMESTAMP, timestamp);

		return object.toString();
	}
	
	public static TerminalTimeoutMessage convertFromJSONString(String jsonString) {
		try {
			return convertFromJSONObject(JSONObject.fromObject(jsonString));
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 每个字段不能为空，否则转换失败
	 * @param jsonObject
	 * @return 转换失败返回null
	 */
	public static TerminalTimeoutMessage convertFromJSONObject(JSONObject jsonObject) {
		TerminalTimeoutMessage message = new TerminalTimeoutMessage();
		try {
            if (jsonObject.containsKey(JSON_KEY_EVENT_TYPE)) {
                EventType eventType = EventType.getItem(CoreJSONUtils.getInt(jsonObject, JSON_KEY_EVENT_TYPE));
                message.setEventType(eventType);
            }

            message.setTerminalId(CoreJSONUtils.getLong(jsonObject, JSON_KEY_TERMINAL_ID));
            message.setTimestamp(CoreJSONUtils.getLong(jsonObject, JSON_KEY_TIMESTAMP));
		} catch (Exception e) {
			return null;
		}
		return message;
	}
	
	public EventType getEventType() {
		return eventType;
	}

	public void setEventType(EventType eventType) {
		this.eventType = eventType;
	}

    public Long getTerminalId() {
        return terminalId;
    }

    public void setTerminalId(Long terminalId) {
        this.terminalId = terminalId;
    }

    public Long getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Long timestamp) {
        this.timestamp = timestamp;
    }
}
